<template>
  <div class="index">
    <div class="reportForms">
      <el-card
        class="card"
        v-for="(item, index) in cardList"
        :key="index"
        style="width: calc(50% - 20px)"
      >
        <div slot="header" class="clearfix entry">
          <span class="title">{{ item.title }}</span>
          <el-button @click="filterSevenDays(item)">近7天</el-button>
          <el-button @click="filterthreeMonths(item)">近6月</el-button>
          <el-button @click="customTime(item)">自定义时间</el-button>
        </div>
        <div
          :id="item.id"
          style="width: 100%; height: 500px"
          v-if="item.id !== 'china'"
        ></div>
        <div v-else>
          <EchartsMap ref="eChartMapData" :list="eChartMapData" @getAtlasData="getAtlasData">
          </EchartsMap>
        </div>
      </el-card>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      v-loading="loading"
    >
      <el-button @click="clickDateType('year')">按年份</el-button>
      <el-button @click="clickDateType('monthrange')">按月份</el-button>
      <el-button @click="clickDateType('daterange')">按天数</el-button>
      <el-button @click="clickDateType('datetimerange', 'HOUR')"
        >按小时</el-button
      >
      <el-button @click="clickDateType('datetimerange', 'MINUTE')"
        >按分钟</el-button
      >

      <div v-if="dateType === 'year'" style="margin-top: 20px">
        <el-date-picker
          v-model="yearStart"
          type="year"
          value-format="yyyy"
          placeholder="开始时间"
          @change="changeDate"
        >
        </el-date-picker>
        <el-date-picker
          v-model="yearEnd"
          type="year"
          value-format="yyyy"
          placeholder="结束时间"
          @change="changeDate"
        >
        </el-date-picker>
      </div>

      <div
        v-if="dateType !== 'year' && dateType !== ''"
        style="margin-top: 20px"
      >
        <el-date-picker
          v-model="timePeriod"
          :value-format="
            dateType === 'monthrange'
              ? 'yyyy-MM'
              : dateType === 'daterange'
              ? 'yyyy-MM-dd'
              : dateType === 'datetimerange'
              ? datetimerange === 'HOUR'
                ? 'yyyy-MM-ddTHH'
                : 'yyyy-MM-ddTHH:mm'
              : ''
          "
          :type="dateType"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        >
        </el-date-picker>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmScreeningTime"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  getAddUser,
  getOrderNumber,
  getOrderPriceNumber,
  getRegionalDistribution,
} from "../api/statisticsAdmin/index.js";
import EchartsMap from "../components/index/echartsMap.vue";

export default {
  components: { EchartsMap },
  data() {
    return {
      cardList: [
        { title: "区域订单量", id: "china" },
        { title: "新增用户", id: "addUser" },
        { title: "订单数量", id: "orderNumber" },
        { title: "订单金额", id: "orderPrice" },
      ],
      dialogVisible: false,
      dateType: "",
      datetimerange: "",
      yearStart: "",
      yearEnd: "",
      timePeriod: "",
      dimension: "DAY",
      loading: false,
      tableButton: "",
      tableId: "",
      eChartMapData: [],
      provisionalDate: {
        dimension: "",
        startTime: "",
        endTime: "",
        name: "",
        level: 0,
      },
    };
  },
  mounted() {
    this.cardList.forEach((e) => {
      this.getList("近7天", "", e.id);
    });
  },
  methods: {
    // 获取地图数据
    getAtlasData(e) {
      if (e) {
        this.provisionalDate.name = e.name;
        this.provisionalDate.level = e.level;
        if(e.level === 1){
          if(e.name === '北京市' || e.name === '天津市' || e.name === '上海市' || e.name === '重庆市'){
            this.provisionalDate.level = 2
          }
        }
      }
      this.eChartMapData = [];
      getRegionalDistribution(this.provisionalDate).then((res) => {
        this.eChartMapData = res.data;
        if (!e) {
          this.$refs["eChartMapData"][0].upData(false); //更新数据
        } else {
          this.$refs["eChartMapData"][0].upData(true); //更新数据
        }
        this.loading = false;
        this.dialogVisible = false;
      });
    },
    getList(e, type, tables) {
      this.loading = true;
      let start = "";
      let end = "";
      if (e === "近7天") {
        this.dimension = "DAY";
        start = new Date();
        end = new Date();
        start.setDate(start.getDate() - 6);
        start = this.parseTime(start, "{y}-{m}-{d}");
        end = this.parseTime(end, "{y}-{m}-{d}");
      }
      if (e === "近6月") {
        this.dimension = "MONTH";
        start = new Date();
        end = new Date();
        start.setMonth(start.getMonth() - 5);
        start = this.parseTime(start, "{y}-{m}-{d}");
        end = this.parseTime(end, "{y}-{m}-{d}");
      }
      if (e === "year") {
        this.dimension = "YEAR";
        start = this.yearStart;
        end = this.yearEnd;
        e = `${start}    ${end}`;
      }
      if (e === "custom") {
        // 月份
        if (type === "monthrange") {
          this.dimension = "MONTH";
        }
        // 天数
        if (type === "daterange") {
          this.dimension = "DAY";
        }
        // 精确到小时
        if (type === "datetimerange") {
          this.dimension = this.datetimerange;
        }
        // 精确到分钟
        if (type === "datetimerange") {
          this.dimension = this.datetimerange;
        }
        start = this.timePeriod[0];
        end = this.timePeriod[1];
        e = `${start}    ${end}`;
      }
      if (tables === "china") {
        this.provisionalDate.dimension = this.dimension;
        this.provisionalDate.startTime = start;
        this.provisionalDate.endTime = end;
        this.getAtlasData();
      }
      if (tables === "addUser") {
        // 新增用户
        getAddUser({
          dimension: this.dimension,
          startTime: start,
          endTime: end,
        })
          .then((res) => {
            if (res.code === 200) {
              let a = [];
              let b = [];
              res.data.items.forEach((i) => {
                a.push(i.name);
                // b.push(i.value)
                b.push({ value: i.value, itemStyle: { color: "" } });
              });
              let c = 0;
              let d = [
                "#56DBDD",
                "#4CACF6",
                "#EB775C",
                "#56DBDD",
                "#F0DA61",
                "#56DDBC",
                "#C462D9",
              ];
              b.forEach((k, j) => {
                if (j % 7 === 0) {
                  c = 0;
                }
                k.itemStyle.color = d[c];
                c++;
              });
              echarts
                .init(document.getElementById("addUser"))
                .setOption(this.setData(a, b, e));
            }
          })
          .finally(() => {
            this.handleClose();
            this.loading = false;
          });
      }
      if (tables === "orderNumber") {
        getOrderNumber({
          dimension: this.dimension,
          startTime: start,
          endTime: end,
        })
          .then((res) => {
            if (res.code === 200) {
              let a = [];
              let b = [];
              res.data.items.forEach((i) => {
                a.push(i.name);
                // b.push(i.value)
                b.push({ value: i.value, itemStyle: { color: "" } });
              });
              let c = 0;
              let d = [
                "#56DBDD",
                "#4CACF6",
                "#EB775C",
                "#56DBDD",
                "#F0DA61",
                "#56DDBC",
                "#C462D9",
              ];
              b.forEach((k, j) => {
                if (j % 7 === 0) {
                  c = 0;
                }
                k.itemStyle.color = d[c];
                c++;
              });
              echarts
                .init(document.getElementById("orderNumber"))
                .setOption(this.setData(a, b, e));
            }
          })
          .finally(() => {
            this.handleClose();
            this.loading = false;
          });
      }
      if (tables === "orderPrice") {
        getOrderPriceNumber({
          dimension: this.dimension,
          startTime: start,
          endTime: end,
        })
          .then((res) => {
            if (res.code === 200) {
              let a = [];
              let b = [];
              res.data.items.forEach((i) => {
                a.push(i.name);
                b.push({ value: i.value, itemStyle: { color: "" } });
              });
              let c = 0;
              let d = [
                "#56DBDD",
                "#4CACF6",
                "#EB775C",
                "#56DBDD",
                "#F0DA61",
                "#56DDBC",
                "#C462D9",
              ];
              b.forEach((k, j) => {
                if (j % 7 === 0) {
                  c = 0;
                }
                k.itemStyle.color = d[c];
                c++;
              });
              echarts
                .init(document.getElementById("orderPrice"))
                .setOption(this.setData(a, b, e));
            }
          })
          .finally(() => {
            this.handleClose();
            this.loading = false;
          });
      }
    },
    setData(x, y, title) {
      return {
        title: { text: title },
        tooltip: { trigger: "axis" },
        toolbox: { feature: { saveAsImage: { show: true } } },
        xAxis: {
          type: "category",
          data: x,
          axisLabel: {
            formatter: function (value) {
              return x.length > 20 ? value.split("-").join("\n") : value;
            },
          },
        },
        yAxis: { type: "value" },
        series: { type: "bar", data: y, barWidth: "40%" },
      };
    },
    // 近7日
    filterSevenDays(e) {
      this.getList("近7天", "", e.id);
    },
    // 近三月
    filterthreeMonths(e) {
      this.getList("近6月", "", e.id);
    },
    customTime(e) {
      this.dialogVisible = true;
      this.tableId = e.id;
    },
    // 自定义时间 里面按钮 初始化
    clickDateType(e, e2) {
      this.timePeriod = "";
      this.dateType = "";
      this.yearStart = "";
      this.yearEnd = "";
      this.dateType = e;
      e2 ? (this.datetimerange = e2) : "";
    },
    // 关闭 取消 筛选时间弹窗
    handleClose() {
      this.dialogVisible = false;
      this.timePeriod = "";
      this.dateType = "";
      this.datetimerange = "";
      this.yearStart = "";
      this.yearEnd = "";
    },
    // 确认
    confirmScreeningTime() {
      if (this.dateType === "year") {
        this.getList("year", "", this.tableId);
      } else {
        this.getList("custom", this.dateType, this.tableId);
      }
    },
    changeDate() {
      this.yearStart > this.parseTime(new Date(), "{y}")
        ? (this.yearStart = this.parseTime(new Date(), "{y}"))
        : "";
      this.yearEnd > this.parseTime(new Date(), "{y}")
        ? (this.yearEnd = this.parseTime(new Date(), "{y}"))
        : this.yearEnd > this.yearStart
        ? ""
        : (this.yearEnd = this.yearEnd = this.parseTime(new Date(), "{y}"));
    },
  },
};
</script>

<style lang="scss" scoped>
.reportForms {
  display: flex;
  flex-flow: row wrap;
}

.index {
  .card {
    margin: 10px;

    .entry {
      .title {
        margin-right: 25%;
      }
    }
  }
}
</style>
